package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component // 注册到spring容器中

public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //填充创建时间和创建人
        //strictInsertFill : 字段有值则不处理，没有值则填充字段
        strictInsertFill(metaObject, "createTime", Date.class, new Date());
        strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getCurrentUserId()));
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        //更新时间和更新人
        //setFieldValByName() : 根据字段名设置字段值
        setFieldValByName("updateTime", new Date(),metaObject);
        setFieldValByName("updateBy", String.valueOf(getCurrentUserId()),metaObject);
    }

    private Long getCurrentUserId() {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser!=null){
            return loginUser.getUserId();
        }
        return 1L;
    }
}
